package logic

import (
	"album-api/internal/svc"
	"album-api/internal/types"
	"context"
	"errors"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"grpc-common/album/types/album"
	"listenboos-common/tools"
	"strconv"
	"time"
)

type TrackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func (l *TrackLogic) SaveTrackInfo(token string, req types.SaveTrackReq) (int64, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Minute)
	defer cancel()
	userId, err := tools.ParseToken(token, l.svcCtx.Config.JWT.AccessSecret)
	if err != nil {
		return 0, err
	}
	in := album.SaveTrackReq{}
	err = copier.Copy(&in, &req)
	if err != nil {
		return 0, err
	}
	in.UserId = userId
	res, err := l.svcCtx.AlbumRpc.SaveTrackInfo(ctx, &in)
	if err != nil {
		return 0, errors.New("调用SaveTrackInfo接口失败")
	}
	// method GetCategoryList not implemented
	//var resp []*types.CategoryChild
	return res.Id, nil
}

func (l *TrackLogic) FindUserTrackPage(token string, req types.FindUserTrackReq) (*types.FindUserTrackResp, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Minute)
	defer cancel()
	userId, err := tools.ParseToken(token, l.svcCtx.Config.JWT.AccessSecret)
	if err != nil {
		return nil, err
	}
	in := album.FindUserTrackPageReq{}
	err = copier.Copy(&in, &req)
	if err != nil {
		return nil, err
	}
	in.UserId = userId
	res, err := l.svcCtx.AlbumRpc.FindUserTrackPage(ctx, &in)
	if err != nil {
		return nil, errors.New("调用FindUserTrackPage接口失败")
	}
	var resp []*types.RecordTrack
	err = copier.Copy(&resp, &res.TrackRecords)
	if err != nil {
		return nil, err
	}
	return &types.FindUserTrackResp{RecordTracks: resp}, nil
}
func (l *TrackLogic) RemoveTrackInfo(token string, req types.RemoteTrackReq) error {
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Minute)
	defer cancel()
	userId, err := tools.ParseToken(token, l.svcCtx.Config.JWT.AccessSecret)
	if err != nil {
		return err
	}
	in := album.RemoveTrackInfoReq{}
	//err = copier.Copy(&in, &req)
	//if err != nil {
	//	return nil, err
	//}
	trackId, _ := strconv.ParseInt(req.TrackId, 10, 64)
	in.TrackId = trackId
	in.UserId = userId
	_, err = l.svcCtx.AlbumRpc.RemoveTrackInfo(ctx, &in)
	if err != nil {
		return errors.New("调用RemoveAlbumInfo接口失败")
	}
	// method GetCategoryList not implemented
	//var resp []*types.CategoryChild
	return nil
}

func NewTrackLogicLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TrackLogic {
	return &TrackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}
